import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vc_package/widget/extension.dart';
import 'package:vc_package/widget/video_thumb_utils.dart';

class VideoThumbImage extends StatefulWidget {
  const VideoThumbImage(
      {super.key,
      required this.url,
      this.maxWidth,
      this.maxHeight,
      this.getFile,
      this.margin});

  final String url;
  final double? maxWidth;
  final double? maxHeight;
  final EdgeInsets? margin;
  final ValueChanged<File>? getFile;

  @override
  State<VideoThumbImage> createState() => _VideoThumbImageState();
}

class _VideoThumbImageState extends State<VideoThumbImage> {
  VideoThumbInfo? _videoThumbInfo;

  @override
  void initState() {
    super.initState();
    print(widget.url);
    VideoThumb.getVideoThumbInfo(widget.url,
        onVideoThumbInfoListener: (VideoThumbInfo? thumbInfo) {
      if (thumbInfo?.thumbFile != null) {
        if (widget.getFile != null) {
          widget.getFile!.call(thumbInfo!.thumbFile as File);
        }
      }
      if (mounted) {
        setState(() {
          _videoThumbInfo = thumbInfo;
        });
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  // 根据VideoThumb来显示图片
  Widget buildVideoThumb(BuildContext context) {
    if (_videoThumbInfo != null && _videoThumbInfo!.thumbFile != null) {
      double? imageWidth;
      double? imageHeight;
      if (_videoThumbInfo!.width != null && _videoThumbInfo!.height != null) {
        imageWidth = _videoThumbInfo!.width!.toDouble();
        imageWidth = _videoThumbInfo!.height!.toDouble();
      }

      return Container(
        width: imageWidth,
        height: imageHeight,
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.all(Radius.circular(4.fit)),
        ),
        child: Image.file(
          _videoThumbInfo!.thumbFile!,
          width: imageWidth,
          height: imageHeight,
          fit: BoxFit.cover,
        ),
      );
    }

    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: widget.margin ?? EdgeInsets.all(0),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: widget.maxWidth ?? double.infinity,
          maxHeight: widget.maxHeight ?? double.infinity,
        ),
        child: buildVideoThumb(context),
      ),
    );
  }
}
